package com.chao.common.util;

import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkHttpClientUtil {
    private static long connTimeOut = 30L;
    private static long readTimeOut = 50L;
    private static long writeTimeOut = 90L;
    public static OkHttpClient client = null;

    static {
        client = new OkHttpClient.Builder()
            .connectTimeout(connTimeOut, TimeUnit.SECONDS)
            .readTimeout(readTimeOut, TimeUnit.SECONDS)
            .writeTimeout(writeTimeOut, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .build();
    }

    public OkHttpClientUtil() {
    }


    public static String doGet(String host, String path, Map<String, String> headers, Map<String, String> querys) throws Exception {
        StringBuffer url = new StringBuffer(host + (path == null?"":path));
        if(querys != null) {
            url.append("?");
            Iterator iterator = querys.entrySet().iterator();
            while(iterator.hasNext()) {
                Map.Entry<String, String> e = (Map.Entry)iterator.next();
                url.append((String)e.getKey()).append("=").append((String)e.getValue() + "&");
            }
            url = new StringBuffer(url.substring(0,url.length()-1));
        }
        Request.Builder requestBuilder = new Request.Builder();
        if(headers != null && headers.size() > 0) {
            Iterator iterator = headers.keySet().iterator();
            while(iterator.hasNext()) {
                String key = (String)iterator.next();
                requestBuilder.addHeader(key, (String)headers.get(key));
            }
        }
        Request request = (requestBuilder).url(url.toString()).build();
        Response response = client.newCall(request).execute();
        String responseStr = response.body() == null?"":response.body().string();
        return responseStr;
    }

    public static String doPostMap(String url, Map<String, String> headers, Map<String, String> querys) throws Exception {
        FormBody.Builder formbody = new FormBody.Builder();
        if(null != querys){
            Iterator iterator = querys.entrySet().iterator();
            while(iterator.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry)iterator.next();
                formbody.add((String)elem.getKey(), (String)elem.getValue());
            }
        }

        RequestBody body = formbody.build();
        Request.Builder requestBuilder = (new Request.Builder()).url(url);
        if(headers != null && headers.size() > 0) {
            Iterator iteratorHeader = headers.keySet().iterator();
            while(iteratorHeader.hasNext()) {
                String key = (String)iteratorHeader.next();
                requestBuilder.addHeader(key, (String)headers.get(key));
            }
        }

        Request requet = requestBuilder.post(body).build();
        Response response = client.newCall(requet).execute();
        String responseStr = response.body() == null?"":response.body().string();
        return responseStr;
    }

    public static String doGetForWeChat(String url) {//写好测试一下
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder uriBuilder = null;
        String str = null;
        try {
            uriBuilder = new URIBuilder(url);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            //5,设置请求报文头部的编码
            httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"));
            //6,设置期望服务返回的编码
            httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
            //7，请求服务
            CloseableHttpResponse response = null;
            response = client.execute(httpGet);
            //8，获取请求返回码
            int statusCode = response.getStatusLine().getStatusCode();
            //9如果请求返回码是200，则说明请求成功
            if (statusCode < 400) {
                //10,获取返回实体
                HttpEntity entity = response.getEntity();
                //11,通过EntityUtils的一个工具类获取返回的内容
                str = EntityUtils.toString(entity, "utf-8");
            } else {
                // 读取错误返回信息
                StringBuffer error = new StringBuffer();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                String line1 = null;
                while ((line1=bufferedReader.readLine())!=null) {
                    error.append(line1).append("\n");
                }
                String res=error.toString();
                bufferedReader.close();
                bufferedReader=null;
            }
            response.close();
            client.close();
            return str;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            //System.out.println(" 对于包含特殊字符的url会抛出urisyntaxexception异常");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    public static String doPost(String url, Map<String, String> headers, String sendMessage) throws Exception {

        RequestBody body = FormBody.create(MediaType.parse("application/json"), sendMessage);;
        Request.Builder requestBuilder = (new Request.Builder()).url(url);
        if(headers != null && headers.size() > 0) {
            Iterator iteratorHeader = headers.keySet().iterator();
            while(iteratorHeader.hasNext()) {
                String key = (String)iteratorHeader.next();
                requestBuilder.addHeader(key, (String)headers.get(key));
            }
        }

        Request requet = requestBuilder.post(body).build();
        Response response = client.newCall(requet).execute();
        String responseStr = response.body() == null?"":response.body().string();
        return responseStr;
    }

    public static String doPut(String host, String path, Map<String, String> headers, Map<String, String> querys) throws Exception {
        FormBody.Builder builder = new FormBody.Builder();
        Iterator iterator = querys.entrySet().iterator();

        while(iterator.hasNext()) {
            Map.Entry<String, String> elem = (Map.Entry)iterator.next();
            builder.add((String)elem.getKey(), (String)elem.getValue());
        }

        RequestBody body = builder.build();
        Request.Builder requestBuilder = (new Request.Builder()).url(host + path);
        if(headers != null && headers.size() > 0) {
            Iterator iteratorHeader = headers.keySet().iterator();
            while(iteratorHeader.hasNext()) {
                String key = (String)iteratorHeader.next();
                requestBuilder.addHeader(key, (String)headers.get(key));
            }
        }

        Request requet = requestBuilder.put(body).build();
        Response response = client.newCall(requet).execute();
        String responseStr = response.body() == null?"":response.body().string();
        return responseStr;
    }

    public static void main(String[] args) throws Exception {
//        String res = doPostMap("http://127.0.0.1:8080/sys/api/getUserPermissions?userId=1", null, null);
//        JSONObject json = JSONObject.parseObject(res);
//        JSONArray data = (JSONArray)json.get("data");
//        String str = JSON.toJSONString(data);
//        // Set反序列化
//        Set<String> set = (Set)JSON.parseObject(str, Set.class);
//        System.out.println(res);
    }
}